<template>
  <div class="back">
    <div class="login">
      <h3>叩丁狼商品管理系统</h3>
      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" class="demo-ruleForm">
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入账号">
            <template #prefix>
              <el-icon size="24">
                <User />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码">
            <template #prefix>
              <el-icon :size="24">
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { loginAPI } from './api'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

const ruleFormRef = ref<FormInstance>()

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  username: '',
  password: '',
})

const rules = reactive({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ validator: validatePass, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      //  valid是true代表数据通过校验，可以发送请求
      loginAPI(ruleForm).then((res) => {
        if (res.code === 200) {
          // 1.存token
          localStorage.setItem("token", res.data.tokenHead + res.data.token)
          // 2.跳转
          router.push('/index')
          // 3.提示登录成功
          ElMessage.success('登录成功')
        }
      })
    } else {
      // 校验失败返回false
      ElMessage.error('校验失败')
      return false
    }
  })
}
</script>
 
<style lang = "less" scoped>
.back {
  width: 100%;
  height: 100%;
  background-color: #2d3a4b;
  overflow: hidden;

  .login {
    width: 400px;
    margin: 200px auto 0;

    h3 {
      padding: 20px 0;
      color: #fff;
      text-align: center;
    }

    :deep(.el-input__inner) {
      height: 50px;
    }

    :deep(.el-button--primary) {
      width: 100%;
      height: 50px;
    }
  }
}
</style>